package com.xstudio.pvzreborn.gui.container;

import com.xstudio.pvzreborn.block.BlockNames;
import com.xstudio.pvzreborn.block.entity.BlockEntityPolarCraftingTable;
import com.xstudio.pvzreborn.gui.container.dataslot.IntDataSlot;
import com.xstudio.pvzreborn.gui.container.dataslot.SunshineDataSlot;
import com.xstudio.pvzreborn.handle.OutputOnlySlotHandler;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.SlotItemHandler;
import org.jetbrains.annotations.NotNull;

/**
 * @author Bread_NiceCat
 */
public class ContainerPolarCraftingTable extends BaseContainer<BlockEntityPolarCraftingTable> {
	public ContainerPolarCraftingTable(int windowId, Inventory playerInv, BlockPos pos) {
        super(windowId, ContainerManager.getMenuType(BlockNames.POLAR_CRAFTING_TABLE), playerInv, pos);
	}

	public ContainerPolarCraftingTable(int windowId, Inventory playerInv, @NotNull FriendlyByteBuf buf) {
		this(windowId, playerInv, buf.readBlockPos());
	}

	@Override
	public void init() {
		addItemSlot();
		addDataSlot(new SunshineDataSlot(getSunshineEnergy()));
		addDataSlot(new IntDataSlot(blockEntity::getProcessTime, blockEntity::setProcessTime));
	}

	@Override
	protected void addItemSlot() {
		IItemHandler input = getHandler(Direction.UP);
		for (int l = 0; l < 3; l++) {
			for (int i = 0; i < 3; i++) {
				addSlot(new SlotItemHandler(input, l * 3 + i, 23 + i * 18, 17 + l * 18));
			}
		}
		addSlot(new OutputOnlySlotHandler(getHandler(Direction.DOWN), 0, 139, 35));
	}

	@Override
	public @NotNull ItemStack quickMoveStack(@NotNull Player pPlayer, int pIndex) {
		Slot from = getSlot(pIndex);
		ItemStack item = from.getItem();
		if (pIndex >= 0 && pIndex < 10) {
			ItemStack out = item;
			if (player.addItem(out)) {
				from.set(ItemStack.EMPTY);
				return out;
			}
		} else {
			for (int i = 0; i < 9 || !item.isEmpty(); i++) {
				Slot to = getSlot(i);
				to.safeInsert(item);
			}
		}
		return ItemStack.EMPTY;
	}

}
